package com.example.demo01.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo01.config.StudentExcel;
import com.example.demo01.entity.Result;
import com.example.demo01.entity.Student;
import com.example.demo01.entity.dto.ImportStudentDTO;
import com.example.demo01.entity.dto.StudentDto;
import com.example.demo01.entity.vo.StudentVo;
import com.example.demo01.service.impl.StudentServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

import static com.example.demo01.entity.Student.*;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author 苏阳奕
 * @since 2025-06-12
 */
@RestController
@RequestMapping("/student")
@Tag(name = "学生管理")
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;


    @GetMapping
    @Operation(summary = "分页查询",description = "分页查询信息")
    public Result page(StudentDto studentDto){
        Page<Student> page = new Page<>(studentDto.getPage(), studentDto.getSize());
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        if (studentDto.getSearch()!="" && studentDto.getSearch()!=null)
            wrapper.like(Student::getName,studentDto.getSearch());
        if (studentDto.getStatus()!=null)
            wrapper.like(Student::getStatus,studentDto.getStatus());
        StudentVo studentVo = new StudentVo();
        studentVo.setRows(studentService.list(page,wrapper));
        studentVo.setTotal(page.getTotal());
        return Result.success(studentVo);
    }
    /**
     * 根据id查询学生信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据id查询学生",description = "根据id查询学生信息")
    public Result getById(@PathVariable Long id){
        return Result.success(studentService.getById(id));
    }

    /**
     * 添加学生信息
     * @param student
     * @return
     */
    @PostMapping
    @Operation(summary = "新增学生",description = "新增学生信息")
    public Result add(@RequestBody Student student){
        student.setCreatedAt(LocalDateTime.now());
        student.setUpdatedAt(LocalDateTime.now());
        boolean b = studentService.save(student);
        if (b)
            return Result.success();
        return Result.fail("新增员工失败，请稍后再试！");
    }

    /**
     * 修改学生信息
     * @param student
     * @return
     */
    @PutMapping
    @Operation(summary = "修改学生",description = "修改学生信息")
    public Result update(@RequestBody Student student){
        student.setUpdatedAt(LocalDateTime.now());
        boolean b = studentService.updateById(student);
        if (b)
            return Result.success();
        return Result.fail("修改员工失败，请稍后再试！");
    }


    /**
     * 删除学生信息
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除学生",description = "删除学生信息")
    public Result delete(@PathVariable List<Long> ids){
        boolean b = studentService.removeByIds(ids);
        if (b)
            return Result.success();
        return Result.fail("删除员工失败，请稍后再试！");
    }


    @GetMapping("/export")
    @Operation(summary = "导出学生信息", description = "将学生列表导出为 Excel 文件")
    public void export(HttpServletResponse response) throws IOException {
        List<Student> studentList = studentService.list();

        List<StudentExcel> excelList = studentList.stream().map(student -> {
            StudentExcel excel = new StudentExcel();
            excel.setName(student.getName());
            excel.setStudentNo(student.getStudentNo());
            excel.setGender(student.getGender() != null && student.getGender() ? "男" : "女");            excel.setBirthDate(student.getBirthDate().toString());
            excel.setClassId(student.getClassId());
            excel.setJoinDate(student.getJoinDate().toString());
            excel.setStatus(student.getStatus() ? "在读" : "已离开");
            return excel;
        }).toList();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("学生列表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), StudentExcel.class)
                .autoCloseStream(true)
                .sheet("学生数据")
                .doWrite(excelList);
    }

    @PostMapping("/import")
    @Operation(summary = "导入学生信息", description = "从 Excel 文件中导入学生信息")
    public Result importExcel(@RequestParam("file") MultipartFile file) {
        try {
            ImportStudentDTO listener = new ImportStudentDTO();
            EasyExcel.read(file.getInputStream(), StudentExcel.class, listener).sheet().doRead();
            List<Student> list = listener.getStudentList();
            boolean save = studentService.saveBatch(list);
            if (save) {
                return Result.success("导入成功");
            } else {
                return Result.fail("导入失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("文件读取异常：" + e.getMessage());
        }
    }
}
